from PyQt6.QtGui import QCursor, QPainter, QTextOption, QTextLayout
from matplotlib.figure import Figure
from again.Data_Management_page.DataManagerwidget import Ui_DataManagerwidget
import picture.resources_rc
import sys
from PyQt6 import QtWidgets, QtCore
from PyQt6.QtWidgets import QTableWidget, QVBoxLayout, QLabel, QStackedWidget, QWidget, QApplication, QFileDialog, \
    QMessageBox, QTableWidgetItem, QInputDialog, QPushButton, QScrollArea, QHBoxLayout, QMenu, QDialog, QSizePolicy
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import numpy as np
from PyQt6.QtCore import Qt, QTimer, QCoreApplication, QEvent,pyqtSignal, QObject
import pandas as pd
from matplotlib.animation import FuncAnimation
from TypeSetting_main import TypeSettingWindow
# type_mapping = {
#         "object": object,
#         "float": float
#     }
class HistogramWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.figure = Figure()
        self.canvas = FigureCanvas(self.figure)
        layout = QVBoxLayout(self)
        layout.addWidget(self.canvas)
        self.setLayout(layout)

    def plot_histogram(self, data):
        plt.rcParams['font.sans-serif'] = ['SimHei']
        plt.rcParams['axes.unicode_minus'] = False
        self.figure.clear()
        ax = self.figure.add_subplot(111)

        # 绘制直方图
        try:
            # 绘制直方图
            if pd.api.types.is_numeric_dtype(data):
                ax.hist(data, bins=20, edgecolor='black')
                ax.set_title(f'{data.name} 直方图')
                ax.set_xlabel(f'{data.name}')
                ax.set_ylabel('Frequency')
            else:
                data.value_counts().plot(kind='bar', ax=ax)
                ax.set_title(f'{data.name} 频数图')
                ax.set_xlabel(f'{data.name}')
                ax.set_ylabel(f'Count({data.name})')

            self.canvas.draw()

        except Exception as e:
            # 弹出错误对话框
            QMessageBox.critical(self, "绘图错误", "绘图失败，请更改数据类型重试。错误信息: " + str(e))

    def clear_plot(self):
        self.figure.clear()
        self.canvas.draw()
class CustomPage3(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.histogram = HistogramWidget(parent=self)
        layout = QVBoxLayout(self)
        layout.addWidget(self.histogram)
        self.setLayout(layout)

    def plot_histogram(self, data):
        self.histogram.plot_histogram(data)

    def clear_plot(self):
        self.histogram.clear_plot()

class CustomPage2(QWidget):
    visualize_signal = pyqtSignal(str)  # 定义信号

    def __init__(self, parent=None):
        super().__init__(parent)

        # 创建主布局
        self.main_layout = QVBoxLayout(self)

        # 添加标题行
        self.add_header()

        # 创建一个ScrollArea以处理大量数据
        self.scroll_area = QScrollArea(self)
        self.scroll_area.setWidgetResizable(True)
        self.scroll_content = QWidget()
        self.scroll_layout = QVBoxLayout(self.scroll_content)
        self.scroll_area.setWidget(self.scroll_content)


        # 将ScrollArea添加到主布局中
        self.main_layout.addWidget(self.scroll_area)
        self.setLayout(self.main_layout)  # 确保设置了布局

    # def add_header(self):
    #     header_layout = QHBoxLayout()
    #     for text in ['属性名', '数据类型', '缺失数目', '数据', '操作']:
    #         label = QLabel(text)
    #         label.setStyleSheet("border: 1px solid red;")  # 设置边框以调试
    #         header_layout.addWidget(label)
    #     self.main_layout.addLayout(header_layout)

    def add_header(self):
        header_layout = QHBoxLayout()
        header_labels = ['属性名', '数据类型', '缺失数目', '数据', '操作']

        for text in header_labels:
            label = QLabel(text)
            label.setStyleSheet("border: 1px solid red;")  # 设置边框以调试
            label.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)  # 设置为伸缩策略
            header_layout.addWidget(label)

        self.main_layout.addLayout(header_layout)

    def add_row(self, attr_name, data_type, missing_count, data_summary):
        row_widget = QWidget()
        row_layout = QHBoxLayout(row_widget)

        # 创建并添加每一列
        row_layout.addWidget(QLabel(attr_name))
        row_layout.addWidget(QLabel(data_type))
        row_layout.addWidget(QLabel(str(missing_count)))
        row_layout.addWidget(QLabel(data_summary))

        # 操作按钮
        visualize_button = QPushButton('可视化')
        # 为按钮连接槽函数
        visualize_button.clicked.connect(lambda: self.visualize_signal.emit(attr_name))
        row_layout.addWidget(visualize_button)

        # 将行添加到滚动区域的布局中
        self.scroll_layout.addWidget(row_widget)

    def clear_rows(self):
        # 清除滚动区域的所有行
        while self.scroll_layout.count():
            child = self.scroll_layout.takeAt(0)
            if child.widget():
                child.widget().deleteLater()


class DataManagerApp(QWidget):
    def __init__(self):
        super().__init__()

        self.ui = Ui_DataManagerwidget()
        self.ui.setupUi(self)

        # 创建菜单
        self.createMenus()

        # 绑定按钮点击事件到相应的槽函数
        self.ui.toolButtonP1.clicked.connect(lambda: self.select_page(self.ui.page1))
        self.ui.toolButtonP2.clicked.connect(lambda: self.select_page(self.ui.page2))
        self.ui.toolButtonP3.clicked.connect(lambda: self.select_page(self.ui.page3))

        # 隐藏窗体顶部
        self.setWindowFlags(Qt.WindowType.FramelessWindowHint)
        # 设置鼠标追踪
        self.setMouseTracking(True)
        # 设置拖动相关变量
        self.is_maximized = False
        self.initDrag()

        # 记录初始位置和大小
        self.initial_geometry = self.geometry()

        # 连接窗口控制按钮
        self.ui.pBtnClose.clicked.connect(self.close)
        self.ui.pBtnBig.clicked.connect(self.toggle_maximize)
        self.ui.pBtnSmall.clicked.connect(self.showMinimized)

        # 初始化页面和按钮状态
        self.setup_buttons()

        # 默认选中第一个按钮
        self.select_button(self.ui.toolButtonP1)

        # 创建并添加自定义页面 CustomPage2 到 page2 中
        self.custom_page2 = CustomPage2()
        self.ui.page2.layout().addWidget(self.custom_page2)  # 使用现有的布局
        self.custom_page2.visualize_signal.connect(self.visualize_column)

        # # 创建 CustomPage3 实例
        self.custom_page3 = CustomPage3()
        # 清除现有的布局内容
        while self.ui.page3.layout().count():
            child = self.ui.page3.layout().takeAt(0)
            if child.widget():
                child.widget().deleteLater()

        # 添加 CustomPage3 到 page3
        self.ui.page3.layout().addWidget(self.custom_page3)
        # self.ui.stackedWidget.addWidget(self.custom_page3)   #新增一个页面
        # 初始化uploaded_data
        self.uploaded_data = None  # 用于存储上传的Excel数据
        # 连接 stackedWidget 页面切换信号
        self.ui.stackedWidget.currentChanged.connect(self.on_page_changed)
        # 初始化表头右键菜单功能
        self.init_table_widget_context_menu()

        self.header_labels = {}  # 用于存储表头标签的持久化字典

        self.dialog_open = False
    def init_table_widget_context_menu(self):
        # 获取 tableWidget（在 page1 中）
        table_widget = self.ui.page1.findChild(QTableWidget, "tableWidget")

        if table_widget:
            # 设置行和列的右键菜单
            table_widget.horizontalHeader().setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
            table_widget.verticalHeader().setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)

            # 绑定右键点击事件到槽函数
            table_widget.horizontalHeader().customContextMenuRequested.connect(self.show_horizontal_header_menu)
            table_widget.verticalHeader().customContextMenuRequested.connect(self.show_vertical_header_menu)

    def show_horizontal_header_menu(self, position):
        # 将位置转换为列索引
        column_index = self.ui.tableWidget.horizontalHeader().logicalIndexAt(position)

        # 获取对应列的表头文本
        header_item = self.ui.tableWidget.horizontalHeaderItem(column_index)
        header_text = header_item.text() if header_item else "Unknown"

        # 在水平表头位置显示右键菜单
        header_menu = QMenu(self)
        header_menu.addAction("水平表头操作1", lambda: self.horizontal_header_action1(position, header_text))
        header_menu.addAction("水平表头操作2", self.horizontal_header_action2)
        header_menu.addAction("水平表头操作3", self.horizontal_header_action3)
        header_menu.exec(self.ui.tableWidget.horizontalHeader().mapToGlobal(position))

    def show_vertical_header_menu(self, position):
        # 在垂直表头位置显示右键菜单
        header_menu = QMenu(self)
        header_menu.addAction("垂直表头操作1", self.vertical_header_action1)
        header_menu.addAction("垂直表头操作2", self.vertical_header_action2)
        header_menu.exec(self.ui.tableWidget.verticalHeader().mapToGlobal(position))

    def horizontal_header_action1(self, position, header_text):
        try:
            header = self.ui.tableWidget.horizontalHeader()
            column_index = header.logicalIndexAt(position)
            print("column_index is", column_index)
            if column_index != -1:
                self.show_type_setting_window(column_index, header_text)

                # selected_type_str = self.dialog.get_selected_type()
                # if selected_type_str:
                #     selected_type = type_mapping.get(selected_type_str, str)
                    # 现在可以使用 selected_type 作为 Python 类型进行操作
        except Exception as e:
            print(f"Error in horizontal_header_action1: {e}")
            QMessageBox.critical(self, "错误", f"发生错误: {e}")

    # def show_type_setting_window(self, column_index):
    #     dialog = TypeSettingWindow(column_index, self.ui.tableWidget, self)
    #     dialog.exec()
    # def show_type_setting_window(self, column_index):
    #     dialog = TypeSettingWindow(column_index, self.ui.tableWidget, self)
    #     if dialog.exec() == QDialog.DialogCode.Accepted:
    #         # 获取用户选择的类型
    #         new_type = dialog.get_selected_type()
    #         # 获取当前列名（去掉标签）
    #         column_name = self.ui.tableWidget.horizontalHeaderItem(column_index).text().split('(')[0].strip()
    #         # 更新表头标签的持久化数据结构
    #         new_header_label = f"{column_name} ({new_type.capitalize()})"
    #         self.header_labels[column_name] = new_header_label
    #         try:
    #             if new_type == "float":
    #                 self.uploaded_data[column_name] = self.uploaded_data[column_name].astype(float)
    #             elif new_type == "object":
    #                 self.uploaded_data[column_name] = self.uploaded_data[column_name].astype(str)
    #         except Exception as e:
    #             print(f"Error during type conversion: {e}")  # 捕获并打印异常
    #             QMessageBox.critical(self, "错误", f"类型转换时发生错误: {e}")

    def show_type_setting_window(self, column_index, header_text):
        if self.dialog_open:
            return

        self.set_controls_enabled(False)  # 禁用主窗口控件
        self.dialog_open = True

        dialog = TypeSettingWindow(column_index, header_text, self.ui.tableWidget, self)
        dialog.setModal(True)  # 设置对话框为模态

        try:
            # 显示对话框并等待用户操作
            if dialog.exec() == QDialog.DialogCode.Accepted:
                # 获取用户选择的类型
                new_type = dialog.get_selected_type()
                # 获取当前列名（去掉标签）
                column_name = self.ui.tableWidget.horizontalHeaderItem(column_index).text().split('(')[0].strip()
                # 更新表头标签的持久化数据结构
                new_header_label = f"{column_name} ({new_type.capitalize()})"
                self.header_labels[column_name] = new_header_label
                try:
                    if new_type == "float":
                        self.uploaded_data[column_name] = self.uploaded_data[column_name].astype(float)
                    elif new_type == "object":
                        self.uploaded_data[column_name] = self.uploaded_data[column_name].astype(str)
                except Exception as e:
                    print(f"Error during type conversion: {e}")  # 捕获并打印异常
                    QMessageBox.critical(self, "错误", f"类型转换时发生错误: {e}")
        finally:
            # 确保对话框关闭后恢复主窗口控件的启用状态
            self.dialog_open = False
            self.set_controls_enabled(True)
    def set_controls_enabled(self, enabled: bool):
        # 根据需要禁用和启用主窗口中的控件
        self.ui.tableWidget.setEnabled(enabled)
        self.ui.widgetToolboxTop.setEnabled(enabled)
        self.ui.widgetDataModel.setEnabled(enabled)
        self.ui.widgetToolboxLeft.setEnabled(enabled)


    def horizontal_header_action2(self):
        print("水平表头操作2触发")

    def horizontal_header_action3(self):
        print("水平表头操作3触发")

    def vertical_header_action1(self):
        print("垂直表头操作1触发")

    def vertical_header_action2(self):
        print("垂直表头操作2触发")
    def select_page(self, page):
        if page == self.ui.page1:
            self.show_page1()
        elif page == self.ui.page2:
            self.show_page2()
        elif page == self.ui.page3:
            self.show_page3()

    # 隐藏自带框
    def initDrag(self):
        # 设置鼠标跟踪判断扳机默认值
        self.moveDrag = False

    def mousePressEvent(self, event):
        if (
                event.button() == Qt.MouseButton.LeftButton) and not self.toolButtonsUnderMouse() and self.ui.widgetTop.underMouse():
            if self.is_maximized:
                self.toggle_maximize()
                self.moveDragPosition = event.globalPosition().toPoint() - self.geometry().topLeft()
            else:
                self.moveDragPosition = event.globalPosition().toPoint() - self.pos()
            self.moveDrag = True
            event.accept()

    def mouseMoveEvent(self, event):
        if self.moveDrag:
            self.move(event.globalPosition().toPoint() - self.moveDragPosition)
            event.accept()

    def mouseReleaseEvent(self, event):
        self.moveDrag = False

    def mouseDoubleClickEvent(self, event):
        if event.button() == Qt.MouseButton.LeftButton and self.ui.widgetTop.underMouse():
            self.toggle_maximize()

    def toolButtonsUnderMouse(self):
        return self.ui.pBtnClose.underMouse() or self.ui.pBtnBig.underMouse() or self.ui.pBtnSmall.underMouse()

    def toggle_maximize(self):
        if self.is_maximized:
            self.setGeometry(self.initial_geometry)
            self.is_maximized = False
        else:
            self.initial_geometry = self.geometry()
            self.showMaximized()
            self.is_maximized = True


    # 菜单栏相关逻辑
    def createMenus(self):
        # 创建文件菜单
        self.fileMenu = QtWidgets.QMenu(self)
        # 创建“导入数据”菜单项，并为其添加二级菜单
        self.importDataMenu = QtWidgets.QMenu("导入数据", self)
        self.appendDataAction = self.importDataMenu.addAction("末尾追加")
        self.overwriteDataAction = self.importDataMenu.addAction("覆盖旧数据")

        # 将导入数据的二级菜单添加到文件菜单
        self.fileMenu.addMenu(self.importDataMenu)

        self.goBackAction = self.fileMenu.addAction("返回项目管理页")
        self.exitAction = self.fileMenu.addAction("退出")

        # 连接文件菜单项到槽函数
        self.appendDataAction.triggered.connect(self.append_data)
        self.overwriteDataAction.triggered.connect(self.overwrite_data)
        self.goBackAction.triggered.connect(self.goback)
        self.exitAction.triggered.connect(self.exitApp)

        # 将文件菜单连接到文件按钮
        self.ui.pBtnFile.setMenu(self.fileMenu)


        # 创建文件菜单
        self.editMenu = QtWidgets.QMenu(self)
        self.backAction = self.editMenu.addAction("上一步")
        self.nextAction = self.editMenu.addAction("下一步")

        self.backAction.triggered.connect(self.back)
        self.nextAction.triggered.connect(self.next)

        self.ui.pBtnEdit.setMenu(self.editMenu)

        self.windowsMenu = QtWidgets.QMenu(self)
        self.windowsAction = self.windowsMenu.addAction("窗口")
        self.windowsAction.triggered.connect(self.windows)
        self.ui.pBtnWindow.setMenu(self.windowsMenu)

        self.helpMenu = QtWidgets.QMenu(self)
        self.aboutAction = self.helpMenu.addAction("使用帮助")
        self.aboutAction.triggered.connect(self.about)
        self.ui.pBtnHelp.setMenu(self.helpMenu)
        self.uploaded_data = None  # 用于存储上传的Excel数据


    # 需要定义处理子菜单项点击的槽函数
    def append_data(self):
        # 实现末尾追加数据的逻辑
        pass

    def goback(self):
        pass

    def back(self):
        pass

    def next(self):
        pass

    def exitApp(self):
        QtWidgets.QApplication.quit()

    def edit(self):
        QtWidgets.QMessageBox.information(self, "编辑", "编辑信息")

    def windows(self):
        QtWidgets.QMessageBox.information(self, "窗口", "窗口信息")

    def about(self):
        QtWidgets.QMessageBox.information(self, "关于", "关于信息")


    # 槽函数用于切换页面
    def setup_buttons(self):
        # 绑定按钮点击事件到相应的槽函数
        self.ui.toolButtonP1.clicked.connect(lambda: self.select_button(self.ui.toolButtonP1))
        self.ui.toolButtonP2.clicked.connect(lambda: self.select_button(self.ui.toolButtonP2))
        self.ui.toolButtonP3.clicked.connect(lambda: self.select_button(self.ui.toolButtonP3))

    def select_button(self, button):
        # 取消所有按钮的选中状态
        self.ui.toolButtonP1.setProperty('selected', False)
        self.ui.toolButtonP2.setProperty('selected', False)
        self.ui.toolButtonP3.setProperty('selected', False)

        # 选中当前按钮
        button.setProperty('selected', True)

        # 刷新所有按钮的样式表
        self.ui.toolButtonP1.style().unpolish(self.ui.toolButtonP1)
        self.ui.toolButtonP1.style().polish(self.ui.toolButtonP1)
        self.ui.toolButtonP2.style().unpolish(self.ui.toolButtonP2)
        self.ui.toolButtonP2.style().polish(self.ui.toolButtonP2)
        self.ui.toolButtonP3.style().unpolish(self.ui.toolButtonP3)
        self.ui.toolButtonP3.style().polish(self.ui.toolButtonP3)

    # def restore_header_labels(self):
    #     # 恢复表头标签
    #     for column_name, label in self.header_labels.items():
    #         column_index = self.ui.tableWidget.horizontalHeader().logicalIndexOf(column_name)
    #         if column_index != -1:
    #             header_item = self.ui.tableWidget.horizontalHeaderItem(column_index)
    #             if header_item is not None:
    #                 header_item.setText(label)

    def restore_header_labels(self):
        # 获取表头
        header = self.ui.tableWidget.horizontalHeader()
        model = self.ui.tableWidget.model()  # 获取模型对象

        for column_name, label in self.header_labels.items():
            # 遍历所有列来找到匹配的列名
            for column_index in range(header.count()):
                header_item = model.headerData(column_index, Qt.Orientation.Horizontal)
                if header_item and column_name in header_item:
                    # 更新表头数据
                    model.setHeaderData(column_index, Qt.Orientation.Horizontal, label)
                    print(f"Updated column '{column_name}' to '{label}'")
                    break

    def show_page1(self):
        try:

            self.ui.stackedWidget.setCurrentWidget(self.ui.page1)
            if self.uploaded_data is not None:
                self.populate_table()
                self.restore_header_labels()
        except Exception as e:
            print(f"Error in show_page1: {e}")
            QMessageBox.critical(self, "错误", f"切换到 Page 1 时发生错误: {e}")


    def show_page2(self):
        if self.ui.stackedWidget.currentWidget() != self.ui.page2:
            self.ui.stackedWidget.setCurrentWidget(self.ui.page2)
            print("Switched to page2")
            self.populate_custom_page2()  # 确保在切换页面时填充数据


    def overwrite_data(self):
        filePath, _ = QFileDialog.getOpenFileName(self, "选择Excel文件", "", "Excel Files (*.xls *.xlsx);;All Files (*)")

        if filePath:
            try:
                df = pd.read_excel(filePath)
                self.uploaded_data = df
                print(f"Data loaded: {self.uploaded_data.shape[0]} rows, {self.uploaded_data.shape[1]} columns")
                self.populate_table()  # 填充表格
                self.populate_custom_page2()  # 填充CustomPage2
                self.ui.stackedWidget.setCurrentWidget(self.ui.page1)  # 切换到 page1 页面
            except Exception as e:
                QMessageBox.critical(self, "错误", f"无法加载Excel文件：{str(e)}")
        else:
            QMessageBox.information(self, "取消", "操作已取消")

    def populate_custom_page2(self):
        if self.uploaded_data is not None:
            self.custom_page2.clear_rows()  # 先清除现有行

            # 获取第一列的列名
            first_column_name = self.uploaded_data.columns[0]

            for col in self.uploaded_data.columns:
                # 跳过第一列的统计
                if col == first_column_name:
                    continue
                missing_count = self.uploaded_data[col].isnull().sum()

                if pd.api.types.is_numeric_dtype(self.uploaded_data[col]):
                    # 统计数字数据类型的均值、最小值和最大值
                    mean_value = self.uploaded_data[col].mean()
                    min_value = self.uploaded_data[col].min()
                    max_value = self.uploaded_data[col].max()
                    data_summary = f"均值({mean_value:.2f}), 最小值({min_value:.2f}), 最大值({max_value:.2f})"
                else:
                    # 统计非数字数据类型的唯一值及其计数
                    unique_values = self.uploaded_data[col].value_counts()
                    data_summary = ', '.join([f"{str(val)}({str(count)})" for val, count in unique_values.items()])
                # 使用最新的数据类型
                data_type = str(self.uploaded_data[col].dtype)

                self.custom_page2.add_row(
                    attr_name=col,
                    data_type=data_type,
                    missing_count=missing_count,
                    data_summary=data_summary
                )
        else:
            QMessageBox.warning(self, "No Data", "请先上传数据")

    def on_page_changed(self, index):
        print(f"Page changed to index: {index}")  # 打印页面索引
        print(f"Total pages: {self.ui.stackedWidget.count()}")  # 打印总页面数量
        page = self.ui.stackedWidget.widget(index)
        if page == self.ui.page1:
            self.select_button(self.ui.toolButtonP1)
        elif page == self.ui.page2:
            self.select_button(self.ui.toolButtonP2)
        elif page == self.ui.page3:
            self.select_button(self.ui.toolButtonP3)
    def check_page_data(self):
        if self.uploaded_data is not None:
            self.populate_table()

    # 在QTableWidget中展示数据
    def populate_table(self):
        if self.uploaded_data is not None:
            rows, cols = self.uploaded_data.shape
            self.ui.tableWidget.setRowCount(rows)
            self.ui.tableWidget.setColumnCount(cols)
            self.ui.tableWidget.setHorizontalHeaderLabels(self.uploaded_data.columns)

            for row in range(rows):
                for col in range(cols):
                    item = QTableWidgetItem(str(self.uploaded_data.iat[row, col]))
                    self.ui.tableWidget.setItem(row, col, item)

            self.ui.tableWidget.update()  # 强制刷新表格视图
        else:
            print("No data to populate")

    def show_page3(self):
        print("show_page3 called")
        # 检查数据是否已上传
        if self.uploaded_data is None or self.uploaded_data.empty:
            # 如果未上传数据或数据为空，弹出警告对话框并返回
            QMessageBox.warning(self, "警告", "请先上传有效数据！")
            return

        # 切换到 Page3 并绘制直方图
        self.ui.stackedWidget.setCurrentWidget(self.ui.page3)

        # 检查数据集是否包含至少一列
        if self.uploaded_data.shape[1] == 0:
            QMessageBox.warning(self, "警告", "数据集不包含任何列，无法绘制直方图！")
            return

        # 获取最后一列并绘制直方图
        last_column = self.uploaded_data.columns[-1]
        data = self.uploaded_data[last_column]

        # print(f"Data for histogram: {data.head()}")  # 打印数据检查内容
        # 清除当前图表
        self.custom_page3.clear_plot()
        # 绘制直方图
        self.custom_page3.plot_histogram(data)

    def visualize_column(self, attr_name):
        if self.uploaded_data is not None:
            column_data = self.uploaded_data[attr_name]
            print(f"可视化 {attr_name} 列的数据")
            # 切换到 page3
            # self.ui.stackedWidget.setCurrentWidget(self.custom_page3)
            # 切换到 page3
            self.select_page(self.ui.page3)
            # 使用 CustomPage3 的 plot_histogram 方法
            self.custom_page3.plot_histogram(column_data)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = DataManagerApp()
    window.show()
    sys.exit(app.exec())

